<template>
	<el-dialog :visible.sync="addVisible" @close="$emit('update:addVisible',false)" width="70%" :show-close='false' class="zuhiSuDialog"
	 :closeOnClickModal='false' append-to-body>
		<span slot="title" class="dialog-title">
		  	追溯
			<el-button  size="mini" @click="close" class="popupClose">关闭</el-button>
		</span>
		<div class="penalContent" style="bottom:40px;overflow: auto;padding:0">
			<div class="testBatch">
				<span class="titleInfo">检测单信息</span>
				<div class="penalrow selectw100" style="padding-top:0;">
					<el-table :data="testBatchDetail" style="width: 100%" size="mini" v-if="reload">
						<el-table-column label="序号" fixed width="50px">
							<template slot-scope="scope">
								{{scope.$index+1}}
							</template>
						</el-table-column>
						<el-table-column label="检测单编号" prop="code" fixed width="110px" show-overflow-tooltip>
						</el-table-column>
						<el-table-column property="detectabilityName" min-width="150px" fixed label="能力参数" :show-overflow-tooltip="true">
						</el-table-column>
						<el-table-column property="status" label="批状态" :formatter="formatter">
						</el-table-column>
						<el-table-column property="analystName" label="检测人">
						</el-table-column>
						<el-table-column property="checkerName" label="校核人">
						</el-table-column>
						<el-table-column property="togetherWithName" label="共同完成人" width="100px">
						</el-table-column>
						<el-table-column property="chuangjianren" label="创建人">
						</el-table-column>
						<el-table-column property="createTime" width="100px" label="创建日期" :formatter="formatterDate">
						</el-table-column>
						<el-table-column property="desc" label="备注" min-width="120px" show-overflow-tooltip>
						</el-table-column>
					</el-table>
				</div>
			</div>
			<span class="titleInfo">样品信息</span>
			<div class="penalrow selectw100" style="padding-top:0;height:150px">
				<el-table :data="testSampleData" style="width: 100%" class="testSample" size="mini" highlight-current-row ref="testSample" v-if="reload" @row-click = "handleSampleChange">
					<el-table-column label="序号" fixed min-width="50px">
						<template slot-scope="scope">
							{{scope.$index+1}}
						</template>
					</el-table-column>
					<el-table-column property="taskName" label="任务"  width="120px" :show-overflow-tooltip="true">
						<template slot-scope="scope">
							{{scope.row.taskName == undefined ? '---':scope.row.taskName}}
						</template>
					</el-table-column>
					<el-table-column property="monitorName" width="90px"  label="监测点" :show-overflow-tooltip="true">
					</el-table-column>
					<el-table-column property="code"  width="120px" label="样品编号" :show-overflow-tooltip="true">
					</el-table-column>

					<el-table-column property="qcTypeName" width="100px" label="QC类型">
					</el-table-column>
					<el-table-column property="collectionLeaderName" width="120px" label="现场负责人">
					</el-table-column>
					<el-table-column property="factManName" label="采样人">
					</el-table-column>
					<el-table-column property="factDate" label="采样日期" width="100px" :formatter="formatterDate">
					</el-table-column>
					<el-table-column property="acceptManName" width="100px" label="接样人">
					</el-table-column>
					<el-table-column property="acceptDate" width="100px" label="接样日期" :formatter="formatterDate">
					</el-table-column>

				</el-table>
			</div>
			<!--</div>-->
			<div class="penalrow tabs" style="padding-top:0;">
				<el-tabs v-model="activeName" style="width:100%;">
					<el-tab-pane label="操作记录" name="first">
						<el-table :data="operatRecord" style="width: 100%" size="mini" height="100%">
							<el-table-column label="序号" fixed min-width="50px">
								<template slot-scope="scope">
									{{scope.$index+1}}
								</template>
							</el-table-column>
							<el-table-column property="stepName" label="操作" min-width="160px">
							</el-table-column>
							<el-table-column property="opinion" label="操作意见" min-width="120px">
							</el-table-column>
							<el-table-column property="createTime" label="日期" min-width="120px" :formatter="formatterTime">
							</el-table-column>
							<el-table-column property="createByName" label="操作人" min-width="100px">
							</el-table-column>

						</el-table>
					</el-tab-pane>
					<el-tab-pane label="检测方法" name="second">
						<div>
							<el-form label-width="110px" :inline="false" class="demo-form-inline methodForm" :model="methodForm" ref="method1Form">
								<el-form-item label="方法名称" prop="name">
									<el-col :span="22">
										<el-input size="mini" v-model="methodForm.name" disabled></el-input>
									</el-col>
								</el-form-item>
								<el-form-item label="方法类型" prop="methodType">
									<el-col :span="22">
										<el-select v-model="methodForm.methodType" placeholder="请选择" size="mini" disabled style="width:100%;">
											<el-option v-for="item in methodTypeSelect.itemList" :key="item.code" :label="item.name" :value="item.code">
											</el-option>
										</el-select>
									</el-col>
								</el-form-item>
								<el-form-item label="分组" prop="group">
									<el-col :span="22">
										<el-select v-model="methodForm.group" placeholder="请选择" size="mini" disabled style="width:100%;">
											<el-option v-for="item in groupSelect.itemList" :key="item.code" :label="item.name" :value="item.code">
											</el-option>
										</el-select>
									</el-col>
								</el-form-item>
								<el-form-item label="版本" prop="version">
									<el-col :span="22">
										<el-input size="mini" v-model="methodForm.version" disabled></el-input>
									</el-col>
								</el-form-item>
							</el-form>
						</div>
					</el-tab-pane>
					<el-tab-pane label="仪器信息" name="third" class="third">
						<div style="width:30%;float:left;">
							<el-form label-width="70px" :inline="false" class="demo-form-inline methodForm1" :model="equipForm" ref="method1Form">
								<el-form-item label="仪器名称" prop="name">
									<el-col :span="22">
										<el-input size="mini" v-model="equipForm.name" disabled></el-input>
									</el-col>
								</el-form-item>
								<el-form-item label="仪器类型" prop="equipmentType">
									<el-col :span="22">
										<el-cascader size="mini" :options="mainEquipType" :key = "keyName" v-model="outMainEquip" disabled style="width:100%;">
										</el-cascader>
									</el-col>
								</el-form-item>
								<el-form-item label="仪器编号" prop="code">
									<el-col :span="22">
										<el-input size="mini" v-model="equipForm.code" disabled></el-input>
									</el-col>
								</el-form-item>
								<el-form-item label="规格型号" prop="model">
									<el-col :span="22">
										<el-input size="mini" v-model="equipForm.model" disabled></el-input>
									</el-col>
								</el-form-item>

							</el-form>
						</div>
						<div style="width:70%;float:right;height: 100%;">
							<el-table :data="standardSeries.seriesRow" style="width: 100%;height:120px" size="mini" v-if="standardSeries.seriesRow != undefined">
								<el-table-column label="标准系列序号" width="110px" property="title" fixed>
								</el-table-column>
								<el-table-column v-for="col in standardSeries.seriesTitle" :key="col.value" :label="col.label">
									<template slot-scope="scope">
										{{scope.row[col.value]}}
									</template>
								</el-table-column>
							</el-table>
							<div id="seriesLine" style="height:calc(100% - 130px);width:90%;overflow:auto;margin:auto"></div>
						</div>

					</el-tab-pane>
					<el-tab-pane label="附件" name="fourth">
						<el-table :data="attachmentList" style="width: 100%" size="mini" key="attachmentList" height="calc(100% - 36px)">
							<el-table-column label="序号" fixed min-width="50px">
								<template slot-scope="scope">
									{{scope.$index+1}}
								</template>
							</el-table-column>
							<el-table-column property="fileName" label="附件名称" min-width="160px">
							</el-table-column>
							<el-table-column property="fileSize" label="附件大小" min-width="100px">
								<template slot-scope="scope">
									{{scope.row.fileSize == 0 ? 1 : scope.row.fileSize }} KB
								</template>
							</el-table-column>
							<el-table-column property="createByName" label="上传人" min-width="80px">
							</el-table-column>
							<el-table-column property="createTime" label="上传时间" min-width="100px" :formatter="timeFormatter">
							</el-table-column>
							<el-table-column label="操作" min-width="100px">
								<template slot-scope="scope">
									<el-button type="text" size="mini" @click="deleteattachment(scope.row)">删除</el-button>
									<el-button type="text" size="mini" @click="downloadattachment(scope.row)">下载</el-button>
									<el-button type="text" size="mini" @click="previewFile(scope.row)">预览</el-button>
								</template>
							</el-table-column>
						</el-table>
					</el-tab-pane>


				</el-tabs>
			</div>
		</div>
	</el-dialog>

</template>

<script>
	import { mapState } from 'vuex'

	export default {
		data() {
			return {

				testSampleData: [],
				testBatchDetail: [],
				activeName: 'first',
				reload: true,
				qcResult: [], //质控样品
				operatRecord: [], //样品操作记录
				methodForm: {}, //检测方法
				equipForm: {},//仪器信息
				mainEquipType: [],
				outMainEquip: [],
				attachmentList: [], //附件列表
				keyName:false,

				standardSeries: {}, //标准系列,

			}
		},
		props: ['testpanelData', 'addVisible'],
		components: {

		},

		computed: {
			...mapState(['testBatchStatus', 'groupSelect', 'methodTypeSelect']),
		},
		mounted() {
			this.$store.dispatch('dogetDictionary');
		},
		watch: {
			addVisible(val, oldVal) {
				if (val) {
					this.batchInfo();
				}
			},
			activeName(val) {
				if (val == "second") {
					this.readMethod()
				} else if (val == "third") {
					this.getEquipment();
					this.getCriterion();
				} else if (val == "fourth") {
					this.getFilePath();
				}
			}


		},
		methods: {
			timeFormatter(row, column, cellValue, index) {
				return this.util.formatterDate({ cellValue: cellValue })
			},
			formatter(row, column, cellValue) {
				return this.util.changeStatus({ cellValue: cellValue, list: this.testBatchStatus })
			},
			formatterDate(row, column, cellValue) {
				return this.util.formatterDate({ cellValue: cellValue })
			},
			formatterTime(row, column, cellValue) {
				return cellValue.slice(0, cellValue.indexOf("."));
			},
			//默认选中第一条样品
			setCurrent(row) {
				this.$nextTick(() => {
					this.$refs.testSample.setCurrentRow(row);
					this.handleSampleChange(row)

				})
			},
			// 是否重新加载
			reLoad() {
				this.reload = false;
				this.$nextTick(() => {
					this.reload = true;
				})
			},
			// 批次信息
			batchInfo() {
				this.$http({
					method: 'post',
					apiUrl: '/detection/batchIntoRecord.htm',
					params: { id: this.testpanelData.id },
					isJson: false,
				}).then(res => {
					if (res.code === 0) {
						this.$set(this.testBatchDetail, 0, res.data)
						this.testSampleData = res.data.tSampleBeans
						for (var i in res.data.tSampleBeans) {
							this.$set(this.testSampleData, i, res.data.tSampleBeans[i])
						}
						this.setCurrent(this.testSampleData[0])
					}
				})
			},


			handleSampleChange(row) {
				this.getsampleRecord(row.sample)
			},
			// 样品操作记录
			getsampleRecord(sample) {
				this.$http({
					method: 'post',
					apiUrl: '/detection/sampleFlowRecord.htm',
					params: {
						sample: sample,
						batch: this.testpanelData.id,
					},
					isJson: false,
				}).then(res => {
					if (res.code === 0) {
						this.operatRecord = res.data;
					}
				})
			},
			// 检测方法
			readMethod() {
				if (this.testpanelData.method == null || this.testpanelData.method == undefined) {
					this.$notify({
						title: '警告',
						message: '找不到方法',
						type: 'warning'
					})
					return;
				}
				this.$http({
					method: 'post',
					apiUrl: '/technology/readMethod.htm',
					params: { id: this.testpanelData.method },
					isJson: false,
				}).then(res => {
					if (res.code === 0) {
						this.methodForm = res.data;
					}
				})
			},
			// 仪器信息
			getEquipment() {
				if (this.testpanelData.equipment == null || this.testpanelData.equipment == undefined) {
					this.$notify({
						title: '警告',
						message: '找不到仪器',
						type: 'warning'
					})
					return;
				}
				this.$http({
					method: 'post',
					apiUrl: '/resource/readEquipment.htm',
					params: { id: this.testpanelData.equipment },
					isJson: false,
				}).then(res => {
					if (res.code === 0) {
						this.equipForm = res.data;
						this.readMainEquipType();
					}
				})

			},
			// /resource/readMainEquipTypeList.htm
			// 读取仪器类型
			readMainEquipType() {
				this.$http({
					method: 'post',
					apiUrl: '/resource/readMainEquipTypeList.htm',
				}).then(res => {
					if (res.code === 0) {
						this.mainEquipType = this.deepClone(res.data);
						this.outMainEquip = this.getTreeDeepArr(this.equipForm.equipmentType, this.mainEquipType)
						this.keyName = true;
					}
				})
			},
			// 处理检测方法数据，id，code转换成value
			deepClone(obj) {
				var result, oClass = this.isClass(obj);
				//确定result的类型
				if (oClass === "Object") {
					result = {};
				} else if (oClass === "Array") {
					result = [];
				} else {
					return obj;
				}
				for (let key in obj) {
					var copy = obj[key];

					if (this.isClass(copy) === "Object") {
						result[key] = this.deepClone(copy);//递归调用
					} else if (this.isClass(copy) === "Array") {

						if (obj['children'].length !== 0) {
							result[key] = this.deepClone(copy);//递归调用
						}
					} else {
						if (key === 'name') {
							result['label'] = obj[key];
						}
						if (key === 'id') {
							result['value'] = obj[key];
						}
						if (key === 'code') {
							result['code'] = obj[key];
						}
						if (key === 'children' && obj[key].length !== 0) {
							result['children'] = obj[key];
						}
					}
				}
				return result;

			},
			//返回传递给他的任意对象的类
			isClass(o) {
				if (o === null) return "Null";
				if (o === undefined) return "Undefined";
				return Object.prototype.toString.call(o).slice(8, -1);
			},
			getTreeDeepArr(key, treeData) {
				let arr = []; // 在递归时操作的数组
				let returnArr = []; // 存放结果的数组
				let depth = 0; // 定义全局层级
				// 定义递归函数
				function childrenEach(childrenData, depthN) {
					for (var j = 0; j < childrenData.length; j++) {
						depth = depthN; // 将执行的层级赋值 到 全局层级
						arr[depthN] = (childrenData[j].value);
						if (childrenData[j].value == key) {
							// returnArr = arr; // 原写法不行, 因 此赋值存在指针关系
							returnArr = arr.slice(0, depthN + 1); //将目前匹配的数组，截断并保存到结果数组，
							break
						} else {
							if (childrenData[j].children) {
								depth++;
								childrenEach(childrenData[j].children, depth);
							}
						}
					}
					return returnArr;
				}
				return childrenEach(treeData, depth);
			},
			// 附件
			// 查看附件
			getFilePath() {
				this.$http({
					method: 'post',
					apiUrl: '/download/getFilePathByIds.htm',
					params: { ids: this.testpanelData.id },
					isJson: false,
				}).then(res => {
					if (res.code == 0) {
						this.attachmentList = res.data
					}
				})
			},
			//删除方法附件
			deleteattachment(row) {
				this.$confirm('是否删除', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$http({
						method: 'post',
						apiUrl: '/download/fileDelete.htm',
						params: {
							id: row.id,
						},
						isJson: false,
					}).then(res => {
						if (res.code === 0) {
							this.$message({
								type: 'success',
								message: '删除成功!'
							});
							this.getFilePath()
						}
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			// 下载附件
			downloadattachment(row) {
				var url = "/download/fileDownload.htm"
				let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
				window.open(process.env.baseUrl + url + '?id=' + row.id + "&token=" + token);
			},
			// 预览
			previewFile(row){
				var url = "preview/fileToPdfPreview.htm"
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
				window.open(process.env.baseUrl + url + '?id=' + row.id + "&token=" + token);
			},
			close() {

				this.$emit('update:addVisible', false)
				this.qcResult = [];
				this.operatRecord = [];
				this.activeName = 'first';
				this.methodForm = {};
				this.equipForm = {};
				this.mainEquipType = [];
				this.outMainEquip = [];
				this.keyName = false;

			},
			// 查看标准系列
			getCriterion() {
				var data = {
					equipment: this.testpanelData.equipment,
					curve:this.testpanelData.curve
				};
				this.$http({
					method: 'post',
					apiUrl: '/detection/criterionMap.htm',
					params: data,
					isJson: false,
				}).then(res => {
					if (res.code === 0) {
						if (res.data != undefined) {
							this.standardSeries = res.data;
							this.standardSeries.seriesRow = []; //表两行数据
							this.standardSeries.seriesTitle = []; //表头数据
							if (this.standardSeries.series != undefined) {
								for (var i in this.standardSeries.series) {  //组装表头
									var obj = {};
									obj.value = this.standardSeries.series[i].seriesSort;
									obj.label = this.standardSeries.series[i].seriesSort;
									this.standardSeries.seriesTitle.push(obj);
								}
							}

							for (var k = 0; k < 2; k++) {//渲染标准系列表的内容
								var childObj = {};
								if (this.standardSeries.series != undefined) {
									for (var i in this.standardSeries.series) {
										if (k == 0) {
											childObj.title = '标准系列浓度';
											childObj[this.standardSeries.series[i].seriesSort] = this.standardSeries.series[i].seriesConcen;

										} else if (k == 1) {
											childObj.title = '标准系列信号值';
											childObj[this.standardSeries.series[i].seriesSort] = this.standardSeries.series[i].signal;
										}
									}
								}


								this.standardSeries.seriesRow.push(childObj)
							}
							// 组装图谱中的点位数据 数据格式为[[x,y],[x,y]]
							var arr = [];
							if (this.standardSeries.series != undefined) {
								for (var i in this.standardSeries.series) {
									var childArr = [];
									childArr[0] = this.standardSeries.series[i].seriesConcen;
									childArr[1] = this.standardSeries.series[i].signal;
									arr.push(childArr)
								}
							}
							var cron = "y = " + this.standardSeries.slope + '* x +' + this.standardSeries.deviation //直线表达式
							var that = this;
              setTimeout(function(){
                that.drawLine(arr, cron)
              },200)
						}
					}

				})
			},
			drawLine(arr, cron) {//arr是点位数据，cron是表达式
				let seriesLine = this.$echarts.init(document.getElementById('seriesLine'))
				// 绘制图表
				var dataAll = arr; //所有点位

				// 取所有点中x轴最大数据和y轴最大数据,用来控制x轴和y轴长度
				var xMax = null;
				var yMax = null;
				for (var i in arr) {
					xMax = (xMax < arr[i][0]) ? arr[i][0] : xMax;
					yMax = (yMax < arr[i][1]) ? arr[i][1] : yMax;
				}
        console.log(dataAll)
				var markLineOpt = {
					animation: false,
					label: {
						normal: {
							formatter: cron,
							textStyle: {
								align: 'right'
							}
						}
					},
					lineStyle: {
						normal: {
							type: 'solid'
						}
					},
					tooltip: {
						formatter: cron
					},
					data: [
						[{
							coord: arr[0],
							symbol: 'none'
						}, {
							coord: arr[arr.length - 1],
							symbol: 'none'
						}]
					]
				};
				seriesLine.setOption({
					title: {
						text: '曲线图谱',
						x: 'center',
						y: 0,
						textStyle: {
							fontSize: 14
						}
					},
					grid: [
						{ x: 'center', y: 'center', width: '80%', height: '80%' },
					],
					tooltip: {
						formatter: 'Group {a}: ({c})'
					},
					xAxis: [
						{ gridIndex: 0, min: 0, max: xMax },
					],
					yAxis: [
						{ gridIndex: 0, min: 0, max: yMax },
					],
					series: [
						{
							name: 'I',
							type: 'scatter',
							xAxisIndex: 0,
							yAxisIndex: 0,
							data: dataAll,
							markLine: markLineOpt,
							itemStyle: {
								color: '#409EFF'
							}
						}
					]
				});
			}
		}
	}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
	.zuhiSuDialog .el-dialog {
		margin-top: 10vh !important;
		height: 80%;
	}
	.zuhiSuDialog .testSample{
		height:100%;
	}
	.zuhiSuDialog .testSample .el-table__fixed-body-wrapper, .testSample .el-table__body-wrapper{
		height: calc(100% - 36px);
    	overflow-y: auto;
	}
	.zuhiSuDialog .el-dialog .el-dialog__body {
		height: calc(100% - 40px);
		padding: 10px;
	}
	.zuhiSuDialog .penalContent{
		bottom: 0 !important;
	}

	.zuhiSuDialog .el-dialog .el-dialog__body .testBatch {
		height: 105px;
	}

	.zuhiSuDialog .el-dialog .el-dialog__body .titleInfo {
		height: 28px;
		display: inline-block;
		line-height: 28x;
		padding-left: 20px;
	}

	.zuhiSuDialog .el-dialog .el-dialog__body .methodForm .el-form-item {
		margin-bottom: 10px;
		width: calc(100%/2);
		float: left;
	}

	.zuhiSuDialog .el-dialog .el-dialog__body .methodForm1 .el-form-item {
		margin-bottom: 10px;
		width: 100%;
		float: left;
	}

	.zuhiSuDialog .tabs {
		height: calc(100% - 285px);
	}

	.zuhiSuDialog .tabs .el-tabs__content {
		height: calc(100% - 45px);
		overflow: auto;
	}

	.zuhiSuDialog .tabs .el-tabs__content .el-tab-pane,
	.zuhiSuDialog .tabs .el-tabs__content .el-tab-pane .el-table {
		height: 100%;
	}
	.zuhiSuDialog .tabs .el-tabs__content .el-tab-pane.third{
		height:400px;

	}
</style>
